package java2instruction;

import java.util.*;
import java.util.Iterator;
import static java2instruction.Kind.*;

public class SymbolTable extends ArrayList<Symbol> {
        private int level;
        
        public SymbolTable() {
        	level = 0;
        }
        
        public Symbol find(String name) {
        	for (Symbol s : this) {
        		if (name.equals(s.getName())) {
        			return s;
        		}
        	}
        	return null;
        }
        
        public Symbol create(String name, Kind kind, String type) {
        	Symbol s = new Symbol(name, kind, level, type);
        	add(s);
        	return s;
        }
        
        public void init() {
        	Symbol s = new Symbol("main", UFUNC, 0, "");
        	add(s);
        }
        
        public void move() {}
        
        public void blkPush() {
        	setLevel(getLevel() + 1);
        }
        
        public void blkPop() {
        	Iterator<Symbol> it = iterator();
	        while (it.hasNext()) {
	        	Symbol s = it.next();
	        	if (getLevel() == s.getBlockLevel()) {
	        		it.remove();
	        	}
	        }
	        setLevel(getLevel() - 1);        	
        }

        public int getLevel() {
            return level;
    }

    public void setLevel(int i) {
            level = i;
    }
    
    public Symbol lookUP(String name, Kind kind, String type) {
        Symbol symb = new Symbol();
        symb = this.find(name);
        if ((symb == null) || (symb.getBlockLevel() < symb.getBlockLevel())) { 
                symb = this.create(name, kind, type);
        }
        else if (name.equals("main")){
                symb.setKind(FUNC);
        }
        return symb;
    }   
    
    public String toString() {
    	String str = "";
        str += "\n^^^^^^^^^^^^^^^^^^^^^^";
        str += "\nNivel Actual de TS: " + getLevel();
        for (Symbol s : this) {   
        	str +=" \n----------------------";
            str += "\nNombre: "+ s.getName();
            str += "\nNivel: " + s.getBlockLevel();
            str += "\nTipo: " + s.getKind();
        }
        str += "\n----------------------";
        return str;
    }  
}